using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using Framework;
using LuaInterface;




    [RequireComponent(typeof(TextMeshProUGUI))]
    public class TMPHyperLinkClick : MonoBehaviour, IPointerClickHandler
    {
        private static Camera _uiCamera;
        private static Camera _PCamera
        {
            get
            {
                if (null == _uiCamera)
                {
                    _uiCamera = GameObject.Find("UIRoot").GetComponent<Canvas>().worldCamera;
                }
                return _uiCamera;
            }
        }

        private TextMeshProUGUI _meshText;
        private TextMeshProUGUI _PMeshText
        {
            get
            {
                if (null == _meshText)
                {
                    _meshText = GetComponent<TextMeshProUGUI>();
                }
                return _meshText;
            }
        }

        private GeneralCallBack _onClick;

        public void SetClickListener(LuaFunction cb, LuaTable cbObj)
        {
            GeneralCallBack.GetOrReUse(ref _onClick, cb, cbObj);
        }

        [LuaInterface.NoToLua]
        public void OnPointerClick(PointerEventData eventData)
        {
            int linkIdx = TMP_TextUtilities.FindIntersectingLink(_PMeshText, eventData.pointerCurrentRaycast.screenPosition, _PCamera);
            if (-1 != linkIdx)
            {
                TMP_LinkInfo linkInfo = _PMeshText.textInfo.linkInfo[linkIdx];
                //Debug.Log($"linkInfo.GetLinkID = {linkInfo.GetLinkID()} linkInfo.GetLinkText = {linkInfo.GetLinkText()} ");
                if (null != _onClick)
                {
                    string url = linkInfo.GetLinkID();
                    GeneralCallBack.Invoke(ref _onClick, url, eventData.position);
                }
            }
        }

        private void OnDestroy()
        {
            GeneralCallBack.RecycleInst(ref _onClick);
        }
    }


